<?php
namespace swift\oss\driver;

use swift\Loader;

class aliyun{
    protected $bucket;

    protected $config = [
        'key'                  =>  '',
        'secret'               =>  '',
        'domain'               =>  ''
    ];

    protected $ossClient;   // OSSClient实例

    public function __construct($config = []){
        // 注册命名空间
        Loader::addNamespace('OSS' , CORE_PATH . 'oss' . DS . 'driver' . DS . 'aliyun' . DS);

        if(!empty($config)){
            $this->config = array_merge($this->config , $config);
        }

        // OSSClient实例
        $this->ossClient = new \OSS\OssClient($this->config['key'],$this->config['secret'],$this->config['domain'] , true);

        $this->bucket = $this->config['bucket'];
    }

    /**
     * 上传指定的本地文件
     * @param string $file  源文件
     * @param string $dir  示例：common/a.jpg
     * @return void
     */
    public function upload($file, $dir){
        if(!$this->existdir(dirname($dir))){
            $this->createdir(dirname($dir));
        }
        $res = $this->ossClient->uploadFile($this->bucket , $dir , $file);
        return $res['info']['url'];
    }

    /**
     * 删除文件
     * @param $dir
     * @return bool
     */
    public function delete($dir){
        $this->ossClient->deleteObject($this->bucket , $dir);
        return true;
    }

    /**
     * 创建目录
     * @param $dir
     * @return void
     */
    public function createdir($dir){
        $this->ossClient->createObjectDir($this->bucket, $dir);
        return true;
    }

    /**
     * 判断目录是否存在
     * @param $dir
     * @return bool
     */
    public function existdir($dir){
        $dir = rtrim($dir , '/') . '/';
        return $this->ossClient->doesObjectExist($this->bucket, $dir);
    }

    /**
     * 判断文件是否存在
     * @param $file
     * @return void
     */
    public function existfile($file){
        $file = rtrim($file , '/');
        return $this->ossClient->doesObjectExist($this->bucket, $file);
    }
}
